package BanyuanClub.Work.项目;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 */
public class CharkServer {
    public volatile int portNumber;
    private JFrame frame;
    JTextField textField;
    JTextField textField_1;
    JComboBox<String> comboBox;
    JButton btnNewButton;
    public ServerSocket server;
    JTextArea textArea = new JTextArea();
    PortText dialog;

    public int index;
    ConcurrentHashMap<String, ObjectOutputStream> pwarr = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, Socket> users = new ConcurrentHashMap<>();

    public ConcurrentHashMap<String, Socket> getUsers() {
        return users;
    }

    /**
     * main方法
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                CharkServer window = new CharkServer();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 链接客户
     */
    public void clientLink(){
                    textArea.append(String.valueOf(portNumber));
        new Thread(() -> {
            if (portNumber == 0) {
                textArea.append("请先设置端口号\n");
            } else {
                try {
                    server = new ServerSocket(portNumber);
                    textArea.append("服务端已启动\n");
                    btnNewButton.setEnabled(false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    while (true) {
                        Socket socket = server.accept();
                        textArea.append("服务端已链接\n");
                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        ObjectOutputStream writer = new ObjectOutputStream(socket.getOutputStream());
                        pwarr.put(index++ + "", writer);
                        //客户端
                        new Thread(() -> {
                            while (true) {
                                try {
                                    String st = reader.readLine();
                                    if (st != null) {
                                        if (!st.contains("#")) {
                                            users.put(st, socket);
                                            int i = users.size();
                                            textField_1.setText(i + "人");
                                            comboBox.addItem(st);
                                        } else {
                                            textArea.append(st + "\n");
                                            String[] arr = st.split("#");
                                            for (ObjectOutputStream bw : pwarr.values()
                                            ) {
                                                bw.writeObject(arr[0] + ":" + arr[1]);
                                            }
                                        }
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    /**
     * Create the application.
     */
    public CharkServer() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBackground(SystemColor.activeCaption);
        frame.getContentPane().setBackground(SystemColor.window);
        frame.getContentPane().setForeground(Color.WHITE);
        frame.getContentPane().setLayout(null);

        //端口窗口
        dialog = new PortText(frame);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(false);

        //服务器标签
        JLabel lblNewLabel = new JLabel("服务器");
        lblNewLabel.setForeground(Color.BLUE);
        lblNewLabel.setFont(new Font("Lucida Grande", Font.BOLD, 15));
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        lblNewLabel.setBounds(6, 6, 89, 30);
        frame.getContentPane().add(lblNewLabel);

        //端口设置按钮
        JButton btnNewButton_2 = new JButton("端口设置");
        btnNewButton_2.setBounds(104, 9, 117, 29);
        frame.getContentPane().add(btnNewButton_2);
        btnNewButton_2.addActionListener((e)->{
            dialog.setVisible(true);
        });

        //服务端启动按钮
        btnNewButton = new JButton("启动");
        btnNewButton.setBackground(Color.LIGHT_GRAY);
        btnNewButton.setBounds(233, 9, 117, 29);
        frame.getContentPane().add(btnNewButton);
        btnNewButton.addActionListener(e -> clientLink());

        //文本域
        textArea.setBounds(31, 48, 575, 266);
        frame.getContentPane().add(textArea);

        //文本输入框
        textField = new JTextField();
        textField.setBounds(97, 380, 413, 35);
        frame.getContentPane().add(textField);
        textField.setColumns(10);

        //点击时发送文本框的内容
        JButton btnNewButton_4 = new JButton("发送");
        btnNewButton_4.setBounds(516, 383, 81, 30);
        frame.getContentPane().add(btnNewButton_4);
        btnNewButton_4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!textField.getText().equals("")) {
                    textArea.append("公告:" + textField.getText() + "\n");
                    for (ObjectOutputStream writer : pwarr.values()
                    ) {
                        try {
                            writer.writeObject("公告:" + textField.getText());
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                        textField.setText("");
                    }
                }
            }
        });

        //服务器停止按钮
        JButton btnNewButton_1 = new JButton("停止");
        btnNewButton_1.setBounds(362, 9, 117, 29);
        frame.getContentPane().add(btnNewButton_1);
        btnNewButton_1.addActionListener(e -> {
            try {
                server.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        });

        //退出按钮
        JButton btnNewButton_3 = new JButton("退出");
        btnNewButton_3.setBounds(480, 9, 117, 29);
        frame.getContentPane().add(btnNewButton_3);
        btnNewButton_3.addActionListener(e -> {
            try {
                server.close();
                System.exit(0);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        });

        //标签
        JLabel lblNewLabel_1 = new JLabel("发送消息：");
        lblNewLabel_1.setFont(new Font("Lucida Grande", Font.BOLD, 13));
        lblNewLabel_1.setBounds(31, 384, 65, 26);
        frame.getContentPane().add(lblNewLabel_1);

        //标签
        JLabel lblNewLabel_2 = new JLabel("发送至：");
        lblNewLabel_2.setFont(new Font("Lucida Grande", Font.BOLD, 13));
        lblNewLabel_2.setBounds(31, 345, 61, 16);
        frame.getContentPane().add(lblNewLabel_2);

        //选择信息接收人的复选框
        comboBox = new JComboBox<>();
        comboBox.addItem("所有人");
        comboBox.setBounds(97, 341, 95, 27);

        //标签
        JLabel lblNewLabel_3 = new JLabel("在线人数：");
        lblNewLabel_3.setFont(new Font("Lucida Grande", Font.BOLD, 13));
        lblNewLabel_3.setBounds(480, 345, 65, 16);
        frame.getContentPane().add(lblNewLabel_3);

        //在线人数显示框
        textField_1 = new JTextField();
        textField_1.setBackground(SystemColor.window);
        textField_1.setBounds(545, 338, 61, 30);
        frame.getContentPane().add(textField_1);
        textField_1.setColumns(10);


        frame.getContentPane().add(comboBox);
        frame.setBounds(100, 100, 640, 455);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    //端口设置类
    public class PortText extends JDialog {

        private final JTextField textField;

        /**
         * Create the dialog.
         */
        public PortText(JFrame jframe) {
            super(jframe);
            setBounds(100, 100, 389, 247);
            getContentPane().setLayout(new BorderLayout());
            JPanel contentPanel = new JPanel();
            contentPanel.setBackground(SystemColor.window);
            contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
            getContentPane().add(contentPanel, BorderLayout.CENTER);
            contentPanel.setLayout(null);
            {
                JLabel lblNewLabel = new JLabel("请输入端口号：");
                lblNewLabel.setFont(new Font("Lucida Grande", Font.BOLD, 13));
                lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
                lblNewLabel.setBounds(24, 37, 92, 34);
                contentPanel.add(lblNewLabel);
            }
            {
                textField = new JTextField();
                textField.setBounds(106, 83, 165, 40);
                contentPanel.add(textField);
                textField.setColumns(10);
            }
            {
                JPanel buttonPane = new JPanel();
                buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
                getContentPane().add(buttonPane, BorderLayout.SOUTH);
                {
                    JButton okButton = new JButton("确定");
                    okButton.setActionCommand("OK");
                    buttonPane.add(okButton);
                    getRootPane().setDefaultButton(okButton);
                    okButton.addActionListener((e)->{
                        portNumber = Integer.parseInt(textField.getText());
                        dialog.setVisible(false);
                    });
                }
                {
                    JButton cancelButton = new JButton("取消");
                    cancelButton.setActionCommand("Cancel");
                    buttonPane.add(cancelButton);
                    cancelButton.addActionListener((e)->{
                        textArea.append("端口号未设置\n");
                        dialog.setVisible(false);
                    });
                }
            }
        }

    }
}
